package de.lulusoft.anothertorrent.core.rtorrent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

import de.lulusoft.anothertorrent.core.AnotherTorrentCore;

public class PeerComments implements Serializable {

	private static final long serialVersionUID = 3824551657853553619L;
	
	private static final String FILENAME = "peerComments";
	private static PeerComments instance = null;

	private HashMap<String, String> comments = null;
	
	public static PeerComments getINSTANCE()
	{
		if (instance == null)
			instance = load();
		return instance;
	}
	
	private PeerComments()
	{
		comments = new HashMap<String, String>();
	}
	
	public void setComment(String id, String comment)
	{
		comments.put(id, comment);
		save();
	}
	
	public String getComment(String id)
	{
		String cmt = comments.get(id);
		if (cmt == null)
			cmt = "";
		return cmt;
	}
	
	private void save()
	{
		FileOutputStream fOut=null;
		ObjectOutputStream oOut=null;
   
		try
		{
			fOut= new FileOutputStream(AnotherTorrentCore.getDefault().getStateLocation()
					+ "/" + FILENAME);
			oOut = new ObjectOutputStream(fOut);
			oOut.writeObject(this);
			
		}catch(IOException e){
			e.printStackTrace(); 
		}finally
		{
			try 
			{
			    oOut.flush();
			    oOut.close();
			    fOut.close();
			} catch (IOException e1) 
			{
				e1.printStackTrace();
			}
		}
	}
	
	private static PeerComments load()
	{
		String filename = AnotherTorrentCore.getDefault().getStateLocation()
		+ "/" + FILENAME;
		if (new File(filename).exists())
		{
			FileInputStream fIn = null;
			ObjectInputStream oIn = null;
	   
			try
			{
				fIn= new FileInputStream(filename);
				oIn = new ObjectInputStream(fIn);
				PeerComments mgr = (PeerComments) oIn.readObject();
				return mgr;
			}catch(IOException e)
			{
				e.printStackTrace(); 
			}catch(ClassNotFoundException e)
			{
				e.printStackTrace(); 
			}finally
			{
				try 
				{
					oIn.close();
					fIn.close();
				} catch (IOException e1) 
				{
					e1.printStackTrace();
				}
			}
		}
		return new PeerComments();
	}
}
